// Package service responsible for interacting with developers
package service

import (
	"gitee.com/wangqiOvO/mapper-go-sdk/internal/common"
	"gitee.com/wangqiOvO/mapper-go-sdk/internal/config"
	"gitee.com/wangqiOvO/mapper-go-sdk/internal/di"
	"gitee.com/wangqiOvO/mapper-go-sdk/internal/event"
	"k8s.io/klog/v2"
	"os"
)

// Main the entrance to mapper
func Main(serviceName string,deviceInterface interface{}) {
	// TODO fix bugs and to be thread safety
	var err error
	var c config.Config
	klog.InitFlags(nil)
	defer klog.Flush()
	ms = &MapperService{}
	if err = ms.MapperServiceInit(serviceName, c,deviceInterface); err != nil {
		klog.Fatal(err)
		os.Exit(1)
	}
	for k,v := range ms.deviceInstances{
		tempK := k
		tempV := v
		for _,visitorV := range tempV.PropertyVisitors{
			tempVisitorV := visitorV
			driverName := common.DriverPrefix+tempK+visitorV.PropertyName
			ms.dic.Update(di.ServiceConstructorMap{
				driverName:func(get di.Get) interface{}{
					return ms.driver.SetConfig(tempV.PProtocol.ProtocolCommonConfig,tempVisitorV.VisitorConfig,tempV.PProtocol.ProtocolConfigs)
				},
			})
		}
	}
	klog.V(1).Info("MapperService Init Successful......")
	err = event.InitTwin(ms.deviceInstances, ms.driver, ms.mqttClient, ms.wg, ms.dic, ms.mutex)
	if err != nil {
		klog.Fatal(err)
		os.Exit(1)
	}
	err = event.InitData(ms.deviceInstances, ms.driver, ms.mqttClient, ms.wg, ms.dic, ms.mutex)
	if err != nil {
		klog.Fatal(err)
		os.Exit(1)
	}
	err = event.InitGetStatus(ms.deviceInstances, ms.driver, ms.mqttClient, ms.wg, ms.dic, ms.mutex)
	if err != nil {
		klog.Fatal(err)
		os.Exit(1)
	}
	err = ms.initSubscribeMqtt()
	if err != nil {
		klog.Fatal(err)
		os.Exit(1)
	}
	ms.wg.Wait()
}

